<?php

function __autoload($className) {
	$name = class2name($className);
	
	$path = DIR_CONTROLLERS . "/" . $name . ".controller.php";
	if (!file_exists($path)) {
		die("$className not found");
	}
	
	require_once $path;
}

function _debug($level=E_ALL) {
	error_reporting($level);
	ini_set("display_errors", "On");
}

/**
 * Dump a variable
 * @param Mixed $variable
 */
function _dump($var) {
	echo "\n\n<pre>\n";
	if(is_array($var) || is_object($var)) {
		print_r($var);
	}else if(is_null($var) || is_bool($var) || $var==="") {
		var_dump($var);
	}else{
		echo $var;
	}
	echo "\n<pre>\n\n";
}

/**
 * Convert URLClassName/FileClassName into real ClassName
 * @param String $url_class_name
 * @return String $class_name
 */
function name2class($name) {
	$name = strtolower($name);
	$className = strtoupper(substr($name,0,1)).substr($name,1);
	$prev=false;
	for ($i=1; $i<strlen($className); $i++) {
		$char = substr($className, $i, 1);
		if($char == "_") {
			$prev=true;
		}else{
			if($prev) {
				$className = substr($className,0,$i) . strtoupper($char) . substr($className, $i+1);
			}
			$prev=false;
		}
	}
	$className = str_replace("_","",$className);
	
	return $className;
}

/**
 * Convert ClassName into URLClassName/FileClassName
 * @param String $class_name
 * @return String $url_class_name
 */
function class2name($className) {
	$name = "";
	for ($i=0; $i<strlen($className); $i++) {
		$char = substr($className, $i, 1);
		if ($char == strtoupper($char) && $i>0) {
			$name .= "_";
		}
		$name .= strtolower($char);
	}
	return $name;
}

/**
 * Call method of a Object
 * @param Object $object
 * @param String $method_name
 * @param Mixed $params
 */
function object_call_method(&$object, $method="index", $params=array()) {
	// build params
	$params = is_array($params) ? $params : array($params);
	foreach ($params as &$param) {
		if(!preg_match('/^\d+$/', $param)) {
			$param = "'".str_replace("'","\\'",$param)."'";
		}
	}
	
	if(!method_exists($object, $method)) {
		die("Method doesn't exist.");
	}
	
	$toeval = '$ret = $object->'.$method.'('.implode(",",$params).');';
	$status = @eval($toeval);
	if($status === false) {
		die("Error evaluating.");
	}
	return $ret;
}

?>